//
//  TSAccountRecordViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/7.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh

enum TSRecordType {
    case unknownType,      // 未知
         investType,       // 投注记录
         rechargeType,     // 充值记录
         withdrawType,     // 提现记录
         conversionType    // 账变明细
}

class TSAccountRecordViewController: TSBaseViewController{
    
    var recordType : TSRecordType!

    var tableController : TSBaseTableViewController!
    lazy var dataSource : [TSRecordModel] = []
    lazy var sectionHeader : TSRecordSectionHeaderView = {
        var header = TSRecordSectionHeaderView.init(sectionTitle: "")
        header.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44)
        header.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        header.delegate = self
        return header
    }()
    
    lazy var recordFilterView : TSRecordFilterView = {
        var filterView = TSRecordFilterView.init(frame: UIScreen.main.bounds)
        filterView.isInvestType = self.recordType == TSRecordType.investType
        filterView.delegate = self
        filterView.isHidden = true
        return filterView
    }()
    
    lazy var detailAlert : TSRecordAlertView = {
        var detail = TSRecordAlertView.init(frame: UIScreen.main.bounds)
        detail.isHidden = true
        return detail
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configViews()
        
        switch recordType {
        case .investType:
            setupNavigationTitle(title: "投注记录")
        case .rechargeType:
            setupNavigationTitle(title: "充值记录")
        case .withdrawType:
            setupNavigationTitle(title: "提现记录")
        case .conversionType:
            setupNavigationTitle(title: "账变明细")
        default:
            setupNavigationTitle(title: "提现")
        }
        
        requestRecordDatas()
    }
    
    @objc func refreshDatas() {
        requestRecordDatas()
        
    }
    
}

//MARK: - TSAccountRecordTableViewCellDelegate
extension TSAccountRecordViewController : TSAccountRecordTableViewCellDelegate {
    
    func didClickRevoke(model: TSRecordModel) {
        revokeOrder(id: "\(model.id)")
    }
}

//MARK: - UITableViewDelegate
extension TSAccountRecordViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if recordType == TSRecordType.investType {

            let model = dataSource[indexPath.row]
            detailAlert.setupView(model: model)
            detailAlert.isHidden = false
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if recordType == TSRecordType.conversionType || recordType == TSRecordType.investType {
            return sectionHeader
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return recordType == TSRecordType.conversionType || recordType == TSRecordType.investType ? 44 : 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

        return UIView.init(frame: CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH), height: T_SafeArea_BottomHeight))
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat(T_SafeArea_BottomHeight)
    }
}

//MARK: - UITableViewDataSource
extension TSAccountRecordViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSAccountRecordTableViewCell.self)) as? TSAccountRecordTableViewCell
        
        if cell == nil {
            cell = TSAccountRecordTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSAccountRecordTableViewCell.self))
        }
        
        cell?.delegate = self
        
        cell?.setupCell(model: dataSource[indexPath.row], last: dataSource.count - 1 == indexPath.row)
        
        return cell!
    }
 
}

//MARK: - TSRecordFilterViewDelegate
extension TSAccountRecordViewController : TSRecordFilterViewDelegate {
    
    func completeFilterCondition(name: String, state: String, startDate: String, endDate: String) {
        
        let status = getStatus(state)
        let qufen = getTypeName(name)
        let startTime = "\(Date.dateStrToTimeInterval(dateStr: startDate))"
        let endTime = "\(Date.dateStrToTimeInterval(dateStr: endDate))"
        
        requestDatasByCondition(status: status, qufen: qufen, startTime: startTime, endTime: endTime)
    }
    
    func completeFilter(status: UInt) {

        TSLog("账变明细筛选\(status)")
        requestDatas(status: "\(status)")
    }
    
    private func getTypeName(_ name:String) -> String {
        switch name {
        case "幸运飞艇":
            return "1"
        case "北京赛车":
            return "2"
        default:
            return "-1"
        }
    }
    
    private func getStatus(_ state:String) -> String {
        switch state {
        case "未开奖":
            return "0"
        case "已派奖":
            return "1"
        case "未中奖":
            return "2"
        case "撤单":
            return "3"
        case "全部":
            return "5"
        default:
            return "-1"
        }
    }
        
}

//MARK: - TSRecordSectionHeaderViewDelegate
extension TSAccountRecordViewController : TSRecordSectionHeaderViewDelegate {
    
    func didClickFilter() {
        recordFilterView.isHidden = false
    }
}

//MARK: - Network Request
extension TSAccountRecordViewController {
    
    /** 获取数据 */
    func requestRecordDatas() {
        
        CBToast.showToastAction()
        
        if recordType == TSRecordType.investType {

            TSNetworkManager.request(TMSNetworkTools.getInvsetRecord(type: nil), showHUD: true, success: { (data) in
                CBToast.hiddenToastAction()
                self.tableController.tableView.mj_header.endRefreshing()
                
                self.dataSource.removeAll()
                let array = data as? Array<Dictionary<String, Any>>
                if array?.count ?? 0 > 0 {
                    for item in array! {
                        var tempModel = TSRecordModel.deserialize(from: item)
                        if tempModel != nil {
                            tempModel?.type = TSRecordType.investType
                            self.dataSource.append(tempModel!)
                        }
                    }
                }
                self.tableController.tableView.reloadData()
            }) { (error) in
                CBToast.hiddenToastAction()
                self.tableController.tableView.mj_header.endRefreshing()
            }
            
        } else {
            var status : String!
            switch recordType {
            case .rechargeType:
                status = "1"
            case .withdrawType:
                status = "100"
            case .conversionType:
                status = "0"
            default: break
            
            }
            requestDatas(status: status)
        }
        
    }
    
    /** 充值、提现、额度转换记录 */
    func requestDatas(status:String) {
        
        TSNetworkManager.request(TMSNetworkTools.getRecord(status: status), showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
            
            self.dataSource.removeAll()
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    var tempModel = TSRecordModel.deserialize(from: item)
                    if tempModel != nil {
                        tempModel?.type = self.recordType!
                        self.dataSource.append(tempModel!)
                    }
                }
            }
            self.tableController.tableView.reloadData()
        }) { (error) in
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
        }
    }
    
    /** 投注筛选 */
    func requestDatasByCondition(status:String, qufen:String, startTime:String, endTime:String)  {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getInvsetFilterRecord(status: status, qufen: qufen, start_time: startTime, end_time: endTime), showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            self.dataSource.removeAll()
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSRecordModel.deserialize(from: item)
                    if let model = tempModel {
                        self.dataSource.append(model)
                    }
                }
            }
            self.tableController.tableView.reloadData()
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 撤单 */
    func revokeOrder(id:String) {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.revokeOrder(id: id), showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                CBToast.showToastAction(message: "撤单成功")
            }
            self.requestRecordDatas()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
}

//MARK: - Initialize
extension TSAccountRecordViewController {
    
    func configViews() {
        
        tableController = TSBaseTableViewController(style: .plain)
        tableController.emptyAlertText = "暂无记录"
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.delegate = self;
        tableController.tableView.dataSource = self
        tableController.tableView.separatorStyle = .none
        tableController.tableView.estimatedRowHeight = 100
        tableController.tableView.rowHeight = UITableView.automaticDimension
        self.view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
        
        UIApplication.shared.keyWindow!.addSubview(recordFilterView)
        UIApplication.shared.keyWindow!.addSubview(detailAlert)
    }
    
    func configTableHeaderView() -> UIView {
        let header = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 58))
        header.backgroundColor = WHITE_COLOR
        
        let searchBtn = UIButton.init(type: .system)
        searchBtn.setTitle("搜索", for: .normal)
        searchBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#484848"), for: .normal)
        searchBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        searchBtn.setEnlargeEdgeNumber(enlarge: 8)
        header.addSubview(searchBtn)
        searchBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(12)
            make.bottom.equalToSuperview().inset(22)
        }
        
        let searchContainer = UIView.init()
        searchContainer.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        searchContainer.layer.cornerRadius = 17
        searchContainer.layer.masksToBounds = true
        header.addSubview(searchContainer)
        searchContainer.snp.makeConstraints { (make) in
            make.centerY.equalTo(searchBtn)
            make.left.equalTo(12)
            make.right.equalTo(searchBtn.snp_left).offset(-10)
            make.height.equalTo(34)
        }
        
        return header
    }
}
